package com.cuitrip.business.pay;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.StrikethroughSpan;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cuitrip.business.bill.ExplainActivity;
import com.cuitrip.business.home.my.card.PromotionActivity;
import com.cuitrip.business.login.LoginInstance;
import com.cuitrip.business.notice.model.FeeDescription;
import com.cuitrip.business.order.model.OrderItem;
import com.cuitrip.business.pay.model.DiscountItem;
import com.cuitrip.business.pay.model.PayMode;
import com.cuitrip.business.pay.presenter.PayDetailPresenter;
import com.cuitrip.business.pay.ui.PayMethodAdapter;
import com.cuitrip.business.tripservice.ui.IconTextView;
import com.cuitrip.business.user.model.CtUserInfo;
import com.cuitrip.component.AutoMatchListView;
import com.cuitrip.component.item.ItemLayout;
import com.cuitrip.component.statelayout.StateLayout;
import com.cuitrip.service.R;
import com.cuitrip.util.ResourceUtil;
import com.cuitrip.util.SpanUtil;
import com.cuitrip.util.time.InputTime;
import com.cuitrip.util.time.OutputTime;
import com.cuitrip.util.time.TimeUtil;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragmentActivity;
import com.lab.jumper.Jumper;
import com.lab.rtenvironment.AppCoreRuntime;
import com.lab.utils.ImageHelper;
import com.lab.utils.NumberUtils;
import com.lab.utils.Utils;
import com.pingplusplus.android.PaymentActivity;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by sheena on 16/2/18.
 */
public class PayOrderPageActivity extends CustomUiFragmentActivity implements com.cuitrip.business.pay.ui.IPayOrderView {


    @Bind(R.id.state_layout)
    StateLayout mStateLayout;

    @Bind(R.id.service_pic)
    ImageView ctServiceAva;


    @Bind(R.id.ct_service_name_tv)
    TextView ctServiceNameTv;

    @Bind(R.id.tv_service_date)
    TextView tvServiceDate;

    @Bind(R.id.ct_service_address_tv)
    TextView tvInsiderInfo;

    @Bind(R.id.ct_order_discounts_tv)
    ItemLayout ctOrderDiscountsTv;

    @Bind(R.id.ct_order_discount)
    TextView ctOrderDiscount;

    @Bind(R.id.tv_transaction_fee)
    TextView tvTransactionFee;

    @Bind(R.id.transaction_fee_layout)
    View transactionFeeLayout;

    @Bind(R.id.order_agency_fee_layout)
    View agencyFeeLayout;

    @Bind(R.id.ct_order_agency_fee)
    TextView agencyFee;

    @Bind(R.id.tv_totalPay)
    TextView tvTotalPay;

    @Bind(R.id.ct_order_normal_price_with_currency_tv)
    TextView tvServicePrice;

    @Bind(R.id.lv_pay_method)
    AutoMatchListView payMethodListView;

    @Bind(R.id.total_block)
    RelativeLayout mTotalBlock;

    @Bind(R.id.arrow)
    IconTextView mArrow;

    @Bind(R.id.pay_fee)
    LinearLayout mPayFee;

    @Bind(R.id.final_pay_currency)
    IconTextView mPayMoneyType;

    @Bind(R.id.pay_tv)
    TextView tvPay;

    private boolean isFeeDetailVisible;


    public static final String TAG = "PayOrderPageActivity";
    public static final String ORDER_ID_KEY = "PayOrderPageActivity.ORDER_ID_KEY";



    private PayDetailPresenter mPayDetailPresenter;
    private String oid;
    private PayMethodAdapter payMethodAdapter;
    private String couponId = "";
    private OrderItem orderItem;
    private String finalPrice;
    private DiscountItem discountItem;
    private ArrayList<FeeDescription> notice;


    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig config = new CustomUiConfig();
        config.mTopbarMiddleAreaName = getString(R.string.payment);
        config.mTopbarLeftAreaName = getString(R.string.back_icon);
        config.mTopbarRightAreaName = getString(R.string.query_icon);
        config.mRightStyle = CustomUiConfig.AreaStyle.ICON_STYLE;
        return config;
    }

    public static void startActivity(Activity context, String orderid) {
        Intent intent = new Intent(context, PayOrderPageActivity.class);
        intent.putExtra(ORDER_ID_KEY, orderid);
        Jumper.launchActivity(context, intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (getIntent() != null && getIntent().hasExtra(ORDER_ID_KEY)) {
            oid = getIntent().getStringExtra(ORDER_ID_KEY);
        } else {
            finish();
            return;
        }
        mPayDetailPresenter = new PayDetailPresenter();
        mPayDetailPresenter.attachView(this);
        super.onCreate(savedInstanceState, R.layout.ct_pay_order);
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);

    }

    @Override
    public void initData() {
        mStateLayout.changeState(StateLayout.State.Loading);
        mPayDetailPresenter.loadPayOrderMode(oid);
    }

    @Override
    public void displayLoading() {
        mStateLayout.changeState(StateLayout.State.Loading);
    }

    @Override
    public void displayContent() {
        mStateLayout.changeState(StateLayout.State.INIT);
    }

    @Override
    public void displayEmpty() {
        mStateLayout.changeState(StateLayout.State.Empty);
    }

    @Override
    public void displayNoNetwork() {
        mStateLayout.changeState(StateLayout.State.NoNetwork);
    }

    @Override
    public void renderServicePartInfo(OrderItem orderItem) {
        this.orderItem = orderItem;
        ImageHelper.displayCtImage(orderItem.getServicePIC(), ctServiceAva, null);
        ctServiceNameTv.setText(orderItem.getServiceName());
        ctServiceNameTv.setMaxLines(1);
        tvServiceDate.setVisibility(View.VISIBLE);

        String formatCommonTime = TimeUtil.formatTime(InputTime.build(orderItem.getServiceDate(), TimeUtil.getZeroZone()), OutputTime.getInstance(OutputTime.OutputType.Type_DAY, TimeUtil.getZeroZone()));
        tvServiceDate.setText(formatCommonTime);
        tvInsiderInfo.setText(orderItem.getServiceAddress() + "/" + orderItem.getUserNick());

    }

    @OnClick(R.id.ct_order_discounts_tv)
    public void clickDiscount() {
        PromotionActivity.startActivity(this, true);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK) {
            DiscountItem discountItem = (DiscountItem) data.getSerializableExtra("discountItem");
            int checkedItemPosition = payMethodListView.getCheckedItemPosition();
            selectDiscount(discountItem, checkedItemPosition);
        }
    }

    public void selectDiscount(DiscountItem discountItem, int position) {
        mPayDetailPresenter.selectDiscount(discountItem, position);
    }

    @Override
    public void renderCouponInfo(DiscountItem discountItem) {
        if (discountItem == null) {
            //优惠券初始值
            SpannableStringBuilder spanBuilder = new SpannableStringBuilder();
            SpannableString colorSpanString = SpanUtil.getColorSpanString(ResourceUtil.getThemeColor(), "CNY");
            colorSpanString.setSpan(new AbsoluteSizeSpan(Utils.dp2pixel(13)), 0, colorSpanString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            spanBuilder.append(colorSpanString);
            spanBuilder.append(" ");
            spanBuilder.append("0.00");
            ctOrderDiscountsTv.setmRightText(spanBuilder);
        } else {
            String couponMoneyType = discountItem.getMoneyType();
            String couponMoney = discountItem.getMoney();
            couponId = discountItem.getCode();
            SpannableStringBuilder builder = new SpannableStringBuilder();
            SpannableString colorSpanString = SpanUtil.getColorSpanString(ResourceUtil.getThemeColor(), couponMoneyType);
            SpannableString string = SpanUtil.getColorSpanString(ResourceUtil.getThemeColor(), couponMoneyType);
            string.setSpan(new AbsoluteSizeSpan(Utils.dp2pixel(13)), 0, colorSpanString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            builder.append(string);
            builder.append(" ");
            builder.append(NumberUtils.getMoneyFormat(couponMoney));
            ctOrderDiscountsTv.setmRightText(builder);
        }
    }

    @Override
    public void renderPriceDetailInfo(DiscountItem discountItem, PayMode payMode) {
        this.finalPrice = payMode.getFinalPrice();
        this.discountItem = discountItem;
        notice = payMode.getNotice();
        String tranFeeIsCharged = payMode.getTranFeeIsCharged();
        String serviceFeeIsCharged = payMode.getServiceFeeIsCharged();

        if (payMode.HIDE.equals(tranFeeIsCharged)){
            tvTransactionFee.setVisibility(View.GONE);
            transactionFeeLayout.setVisibility(View.GONE);
        }else if(payMode.NOT_CHARGE.equals(tranFeeIsCharged) && (!TextUtils.isEmpty(payMode.getPayFee()))) {
            transactionFeeLayout.setVisibility(View.VISIBLE);
            //0不收取,1收取，-1隐藏
            tvTransactionFee.setVisibility(View.VISIBLE);
            SpannableString tranPrice = new SpannableString(NumberUtils.getMoneyFormat(payMode.getPayFee()));
            tranPrice.setSpan(new StrikethroughSpan(), 0, tranPrice.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            tvTransactionFee.setText(tranPrice);
        } else {
            tvTransactionFee.setVisibility(View.VISIBLE);
            transactionFeeLayout.setVisibility(View.VISIBLE);
            tvTransactionFee.setText(NumberUtils.getMoneyFormat(payMode.getPayFee()));
        }

        if (payMode.HIDE.equals(serviceFeeIsCharged)){
            agencyFee.setVisibility(View.GONE);
            agencyFeeLayout.setVisibility(View.GONE);
        }else if (payMode.NOT_CHARGE.equals(serviceFeeIsCharged) && (!TextUtils.isEmpty(payMode.getServiceFee()))) {
            agencyFee.setVisibility(View.VISIBLE);
            agencyFeeLayout.setVisibility(View.VISIBLE);
            SpannableString angencyPrice = new SpannableString(NumberUtils.getMoneyFormat(payMode.getServiceFee()));
            angencyPrice.setSpan(new StrikethroughSpan(), 0, angencyPrice.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            agencyFee.setText(angencyPrice);
        } else {
            agencyFee.setVisibility(View.VISIBLE);
            agencyFeeLayout.setVisibility(View.VISIBLE);
            agencyFee.setText(NumberUtils.getMoneyFormat(payMode.getServiceFee()));
        }
        tvServicePrice.setText(NumberUtils.getMoneyFormat(orderItem.getOrderPrice()));
        mPayMoneyType.setText(orderItem.getPayCurrency());
        ctOrderDiscount.setText("-" + payMode.getCouponFee());
        tvTotalPay.setText(NumberUtils.getMoneyFormat(payMode.getFinalPrice()));
        tvPay.setText(getString(R.string.pay) + " " + orderItem.getPayCurrency() + " " + NumberUtils.getMoneyFormat(finalPrice));
    }


    @Override
    public void renderPayMethodInfo(OrderItem orderItem) {
        if ("0.00".equals(finalPrice)) {
            payMethodListView.setVisibility(View.GONE);
        } else {
            payMethodListView.setVisibility(View.VISIBLE);
            payMethodAdapter = new PayMethodAdapter(PayOrderPageActivity.this, orderItem, payMethodListView);
            payMethodListView.setAdapter(payMethodAdapter);
            if (payMethodListView.getCount() > 0) {
                payMethodListView.setItemChecked(0, true);
            }
        }

    }

    @Override
    public void requestPay(String payParams) {
        Intent intent = new Intent();
        String packageName = getPackageName();
        ComponentName componentName = new ComponentName(packageName, packageName + ".wxapi.WXPayEntryActivity");
        intent.setComponent(componentName);
        intent.putExtra(PaymentActivity.EXTRA_CHARGE, payParams);
        startActivityForResult(intent, REQUEST_CODE_PAYMENT);
    }

    @Override
    public void uiPaySuc() {
        onPaySuccess();
    }

    @Override
    protected void onPaySuccess() {
        String email = "";
        CtUserInfo userInfo = LoginInstance.getInstance().getUserInfo();
        if (userInfo != null) {
            email = userInfo.getEmail();
        }
        PaySucActivity.start(this, email, orderItem, 3);
        finish();
        sendBroadcast(new Intent(OrderItem.ORDER_STATUS_CHANGED_ACTION));
    }

    protected void onPayFailed(String msg) {
        PayFailedActivity.start(PayOrderPageActivity.this, msg);
    }

    protected void onPayCancel() {
        startActivity(new Intent(PayOrderPageActivity.this, PayFailedActivity.class));
    }

    @Override
    public void initListener() {
        payMethodListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                payMethodAdapter.notifyDataSetChanged();
                TextView title = (TextView) view.findViewById(R.id.title);
                //重新请求getFinalPrice接口
                String channel = title.getText().toString();
                mPayDetailPresenter.selectPayMethod(channel, discountItem);
            }
        });
        mTotalBlock.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isFeeDetailVisible) {
                    mArrow.setText(getString(R.string.arrow_down_icon));
                    mPayFee.setVisibility(View.GONE);
                    isFeeDetailVisible = false;
                } else {
                    mArrow.setText(getString(R.string.arrow_up_icon));
                    mPayFee.setVisibility(View.VISIBLE);
                    isFeeDetailVisible = true;
                }
            }
        });
    }

    @OnClick(R.id.pay_tv)
    public void clickPay() {
        int type = payMethodListView.getCheckedItemPosition();
        mPayDetailPresenter.clickPay(tvTotalPay.getText().toString(), type, couponId);
    }

    @Override
    public Context getContext() {
        return AppCoreRuntime.context;
    }

    @Override
    public void onTopbarLeftPress() {
        onBackPressed();
    }

    @Override
    public void onTopbarRightPress() {
        if (notice!=null) {
            Intent intent = new Intent(this, ExplainActivity.class);
            intent.putExtra(ExplainActivity.KEY_CODE, ExplainActivity.SHOW_INFO_ABOUT_FEE_DESCRIPTION);
            intent.putParcelableArrayListExtra("notice", notice);
            ExplainActivity.startActivityBy(this, intent);
        }

    }
}
